#!/usr/bin/python
# -*- coding: utf-8 -*-
# @Time: 20-8-7 下午5:43
# @Author: HuangChuQin
# @Site: 
# @File: bao_stock_service.py
# @Software: PyCharm
import baostock as bs


def get_stock_list():
    """
    查询现阶段A股列表
    :return: (fields, data)
    fields  array   表头名称    [value...]
    data    array   股票信息    [[code,code_name,ipoDate,outDate,type,status]...]
    """
    bs.login()

    rs = bs.query_stock_basic()

    print('query_stock_basic respond error_code:' + rs.error_code)
    print('query_stock_basic respond  error_msg:' + rs.error_msg)

    bs.logout()

    return rs.fields, rs.data


def get_stock_hist_data(code, date=None):
    """
    获取股票信息和历史数据
    :param code: 股票代码 如：sh.000001
    :param date: 查询的开始日期 默认为股票上市日期，即全部数据
    :return: (stock_info,data_list,date_list,volumes)
    stock_info  json    基本信息
    data_list   array   日K数据    [[open,close,low,high,volume]...]
    date_list   array   日期值     [date...]
    volumes     array   成交量     [value...]
    """
    lg = bs.login()

    print('login respond error_code:' + lg.error_code)
    print('login respond  error_msg:' + lg.error_msg)

    rs_basic = bs.query_stock_basic(code)

    print('query_stock_basic\n|-code:%s\n|-error_code:%s\n|-error_msg:%s' % (code, rs_basic.error_code, rs_basic.error_msg))

    stock_info = rs_basic.data[0]

    if date is None:
        date = stock_info[2]

    rs = bs.query_history_k_data_plus(
        code, 'open,close,low,high,volume,date', start_date=date, end_date=None, frequency="d"
    )
    print("query_history_k_data_plus\n|-code:%s\n|-error_code:%s\n|-error_msg:%s" % (code, rs.error_code, rs.error_msg))

    if len(rs.data) == 0:
        print("指定时间没有数据")
        return None

    data_list = []
    date_list = []
    volumes = []
    for datum in rs.data:
        data_list.append(datum[:5])
        date_list.append(datum[5])
        volumes.append(datum[4])

    bs.logout()

    return stock_info, data_list, date_list, volumes
